/*
 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
 *
 * Copyright (C) 2002-2011 Aleph One Ltd.
 *   for Toby Churchill Ltd and Brightstar Engineering
 *
 * Created by Charles Manning <charles@aleph1.co.uk>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

/* mtd interface for YAFFS2 */

#include "yportenv.h"
#include "yaffs_trace.h"

#include "yaffs_mtdif2.h"

#include "linux/mtd/mtd.h"
#include "linux/types.h"
#include "linux/time.h"

#include "yaffs_packedtags2.h"

#include "yaffs_linux.h"

//DEFY
#include "yaffs_defy.h"
#include <linux/random.h>

/* NB For use with inband tags....
 * We assume that the data buffer is of size total_bytes_per_chunk so
 * that we can also use it to load the tags.
 */
int nandmtd2_write_chunk_tags(struct yaffs_dev *dev, int nand_chunk,
			      const u8 *data,
			      const struct yaffs_ext_tags *tags)
{
	struct mtd_info *mtd = yaffs_dev_to_mtd(dev);
#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
	struct mtd_oob_ops ops;
#else
	size_t dummy;
#endif
	int retval = 0;

	loff_t addr;

	struct yaffs_packed_tags2 pt;

	// DEFY: Create a random IV
	u8 *random_iv = kmalloc(dev->iv_length, GFP_KERNEL);

	//	int packed_tags_size =
	//  dev->param.no_tags_ecc ? sizeof(pt.t) : sizeof(pt);
	//void *packed_tags_ptr =
	//  dev->param.no_tags_ecc ? (void *)&pt.t : (void *)&pt;

	u8 cipher[dev->param.total_bytes_per_chunk];
	//defy_printk("nandmtd2_write_chunk_tags", BEGIN_F);

	yaffs_trace(YAFFS_TRACE_MTD,
		    "nandmtd2_write_chunk_tags chunk %d data %p tags %p",
		    nand_chunk, data, tags);

	addr = ((loff_t) nand_chunk) * dev->param.total_bytes_per_chunk;

	/* For yaffs2 writing there must be both data and tags.
	 * If we're using inband tags, then the tags are stuffed into
	 * the end of the data buffer.
	 */
	if (!data || !tags)
		BUG();
	else if (dev->param.inband_tags) {
		struct yaffs_packed_tags2_tags_only *pt2tp;
		pt2tp = (struct yaffs_packed_tags2_tags_only *)
		    (data + dev->data_bytes_per_chunk);
		yaffs_pack_tags2_tags_only(pt2tp, tags);
	} else {
	        yaffs_pack_tags2(&pt, tags, !dev->param.no_tags_ecc);
	}

#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
	//defy_printk_indent();
	//printk("The seq number is %d\n", tags->seq_number);
	ops.mode = MTD_OOB_AUTO;
	//ops.ooblen = (dev->param.inband_tags) ? 0 : packed_tags_size;
	ops.ooblen = dev->iv_length;
	ops.len = dev->param.total_bytes_per_chunk;
	ops.ooboffs = 0;
	// DEFY: Encrypt entire chunk, inband tags and all
	memcpy(cipher, data, dev->param.total_bytes_per_chunk);
	get_random_bytes(random_iv, dev->iv_length);
	defy_cipher(dev, cipher, dev->param.total_bytes_per_chunk,
		    tags->defy_level, random_iv, DEFY_ENCRYPT);
	ops.datbuf = (u8 *) cipher;
	ops.oobbuf = random_iv;
	//ops.datbuf = (u8 *) data;
	//ops.oobbuf = (dev->param.inband_tags) ? NULL : packed_tags_ptr;
	if(tags->defy_level > -1) {
	    defy_printk_indent();
	    printk("Writing chunk %d at level %d with seq_number %d\n",
		   nand_chunk, tags->defy_level, tags->seq_number);
	}
	retval = mtd->write_oob(mtd, addr, &ops);
#else
	if (!dev->param.inband_tags) {
		retval =
		    mtd->write_ecc(mtd, addr, dev->data_bytes_per_chunk,
				   &dummy, data, (u8 *) packed_tags_ptr, NULL);
	} else {
		retval =
		    mtd->write(mtd, addr, dev->param.total_bytes_per_chunk,
			       &dummy, data);
	}
#endif

	//defy_printk("nandmtd2_write_chunk_tags", END_F);
	kfree(random_iv);

	if (retval == 0)
		return YAFFS_OK;
	else
		return YAFFS_FAIL;
}

int nandmtd2_read_chunk_tags(struct yaffs_dev *dev, int nand_chunk,
			     u8 *data, struct yaffs_ext_tags *tags)
{
	struct mtd_info *mtd = yaffs_dev_to_mtd(dev);
#if (MTD_VERSION_CODE > MTD_VERSION(2, 6, 17))
	struct mtd_oob_ops ops;
#endif
	int retval = 0;
	int local_data = 0;

	// DEFY
	int chunk_cached = -1;

	loff_t addr = ((loff_t) nand_chunk) * dev->param.total_bytes_per_chunk;

	struct yaffs_packed_tags2 pt;

	int packed_tags_size =
	    dev->param.no_tags_ecc ? sizeof(pt.t) : sizeof(pt);
	void *packed_tags_ptr =
	    dev->param.no_tags_ecc ? (void *)&pt.t : (void *)&pt;

	//printk("nandmtd2_read_chunk_tags\n");
	yaffs_trace(YAFFS_TRACE_MTD,
		"nandmtd2_read_chunk_tags chunk %d data %p tags %p",
		nand_chunk, data, tags);

	if (dev->param.inband_tags) {
		if (!data) {
			local_data = 1;
			data = yaffs_get_temp_buffer(dev);
		}
	}

#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
	if (dev->param.inband_tags || (data && !tags)) {
	        // DEFY: This should always be chosen, DEFY uses inband tags
	        retval = defy_read_cached_chunk(dev, nand_chunk,
						data, tags);
		chunk_cached = retval;
		if(retval == -1) {
		    // DEFY: The chunk was not cached
		    ops.mode = MTD_OOB_AUTO;
		    ops.ooblen = dev->iv_length;
		    ops.len = dev->param.total_bytes_per_chunk;
		    ops.ooboffs = 0;
		    ops.datbuf = data;
		    ops.oobbuf = yaffs_dev_to_lc(dev)->spare_buffer;
		    retval = mtd->read_oob(mtd, addr, &ops);
		    // DEFY: Tags will be passed in to this function with
		    //         the level already set
		    defy_cipher(dev, data, dev->param.total_bytes_per_chunk,
				tags->defy_level, ops.oobbuf, DEFY_DECRYPT);
		}
	} else if (tags) {
		ops.mode = MTD_OOB_AUTO;
		ops.ooblen = packed_tags_size;
		ops.len = data ? dev->data_bytes_per_chunk : packed_tags_size;
		ops.ooboffs = 0;
		ops.datbuf = data;
		ops.oobbuf = yaffs_dev_to_lc(dev)->spare_buffer;
		retval = mtd->read_oob(mtd, addr, &ops);
	}
#else
	if (!dev->param.inband_tags && data && tags) {
		retval = mtd->read_ecc(mtd, addr, dev->data_bytes_per_chunk,
				       &dummy, data, dev->spare_buffer, NULL);
	} else {
		if (data)
			retval =
			    mtd->read(mtd, addr, dev->data_bytes_per_chunk,
				      &dummy, data);
		if (!dev->param.inband_tags && tags)
			retval =
			    mtd->read_oob(mtd, addr, mtd->oobsize, &dummy,
					  dev->spare_buffer);
	}
#endif

	if(chunk_cached != -1) {
	    // DEFY: The chunk was cached, tags were already set
	} else if (dev->param.inband_tags) {
	    // DEFY: If chunk wasn't cached, extract the tags
	    struct yaffs_packed_tags2_tags_only *pt2tp;
	    pt2tp = ((struct yaffs_packed_tags2_tags_only *)
		     &data[dev->data_bytes_per_chunk]);
	    yaffs_unpack_tags2_tags_only(tags, pt2tp);
	} else {
	        // DEFY: This should never happen
		if (tags) {
			memcpy(packed_tags_ptr,
			       yaffs_dev_to_lc(dev)->spare_buffer,
			       packed_tags_size);
			yaffs_unpack_tags2(tags, &pt, !dev->param.no_tags_ecc);
		}
	}

	if (local_data)
		yaffs_release_temp_buffer(dev, data);

	if (tags && retval == -EBADMSG
	    && tags->ecc_result == YAFFS_ECC_RESULT_NO_ERROR) {
		tags->ecc_result = YAFFS_ECC_RESULT_UNFIXED;
		dev->n_ecc_unfixed++;
	}
	if (tags && retval == -EUCLEAN
	    && tags->ecc_result == YAFFS_ECC_RESULT_NO_ERROR) {
		tags->ecc_result = YAFFS_ECC_RESULT_FIXED;
		dev->n_ecc_fixed++;
	}

	if (retval == 0)
		return YAFFS_OK;
	else
		return YAFFS_FAIL;
}

int nandmtd2_mark_block_bad(struct yaffs_dev *dev, int block_no)
{
	struct mtd_info *mtd = yaffs_dev_to_mtd(dev);
	int retval;
	yaffs_trace(YAFFS_TRACE_MTD,
		"nandmtd2_mark_block_bad %d",
		block_no);

	retval =
	    mtd->block_markbad(mtd,
			       block_no * dev->param.chunks_per_block *
			       dev->param.total_bytes_per_chunk);

	if (retval == 0)
		return YAFFS_OK;
	else
		return YAFFS_FAIL;

}

int nandmtd2_query_block(struct yaffs_dev *dev, int block_no,
			 enum yaffs_block_state *state, u32 *seq_number)
{
	struct mtd_info *mtd = yaffs_dev_to_mtd(dev);
	int retval;

	// DEFY
	u8 *data = kmalloc(dev->data_bytes_per_chunk, GFP_KERNEL);
	u8 *empty_template = kmalloc(dev->data_bytes_per_chunk, GFP_KERNEL);
	// DEFY: I don't think I need the empty template
	memset(empty_template, 0xFF, dev->param.total_bytes_per_chunk);

	yaffs_trace(YAFFS_TRACE_MTD, "nandmtd2_query_block %d", block_no);
	retval =
	    mtd->block_isbad(mtd,
			     block_no * dev->param.chunks_per_block *
			     dev->param.total_bytes_per_chunk);

	if (retval) {
		yaffs_trace(YAFFS_TRACE_MTD, "block is bad");

		*state = YAFFS_BLOCK_STATE_DEAD;
		*seq_number = 0;
	} else {
		struct yaffs_ext_tags t;
		// DEFY: Set tags level here
		t.defy_level = dev->defy_current_level;
		t.chunk_used = 0;
		nandmtd2_read_chunk_tags(dev, block_no *
					 dev->param.chunks_per_block, data, &t);

		// DEFY: Need to figure out how to determine that the first
		//         chunk is data vice random. Or do we?
		if (t.chunk_used) {
			*seq_number = t.seq_number;
			*state = YAFFS_BLOCK_STATE_NEEDS_SCAN;
		} else if(!memcmp(data, empty_template,
				  dev->data_bytes_per_chunk)) {
		    // DEFY: This is a truly empty block
			*seq_number = 0;
			*state = YAFFS_BLOCK_STATE_EMPTY;
		}  else {
		        *state = YAFFS_BLOCK_STATE_FULL;
		}
	}
	yaffs_trace(YAFFS_TRACE_MTD,
		"block is bad seq %d state %d",
		*seq_number, *state);

	memset(data, 0, dev->data_bytes_per_chunk);
	kfree(data);
	kfree(empty_template);

	if (retval == 0)
		return YAFFS_OK;
	else
		return YAFFS_FAIL;
}

